package cn.hwl.springframework.beans.factory.support;

import cn.hwl.springframework.beans.BeansException;
import cn.hwl.springframework.beans.factory.ConfigurableListableBeanFactory;
import cn.hwl.springframework.beans.factory.config.BeanDefinition;
import cn.hwl.springframework.beans.factory.config.BeanPostProcessor;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :  HuangWL
 * @date :    2022/4/22 19:58
 * 1.实现了接口 BeanDefinitionRegistry 中的 registerBeanDefinition（）
 * 2.实现抽象类 AbstractBeanFactory 中定义的抽象方法：getBeanDefinition()
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

    private Map<String,BeanDefinition> beanDefinitionMap = new HashMap<>();

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {

        beanDefinitionMap.put(beanName,beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null){
            throw new BeansException("No bean named '" + beanName + "' is defined");
        }
        return beanDefinition;
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.keySet().forEach(this::getBean);
    }





    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName,beanDefinition)->{
            Class clazz = beanDefinition.getBeanClass();
            if (type.isAssignableFrom(clazz)){
                result.put(beanName, (T) beanDefinition);
            }
        });
        return result;
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

}
